package org.abc.fund.controller.funds;

import org.abc.fund.entity.funds.FundNetValueHistory;
import org.abc.fund.service.funds.FundNetValueHistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;

@RestController
@RequestMapping("/api/netvalue")
public class FundNetValueHistoryController {

    @Autowired
    private FundNetValueHistoryService fundNetValueHistoryService;

    @GetMapping("/{fundCode}")
    public List<FundNetValueHistory> getHistoryByFundCode(@PathVariable String fundCode) {
        return fundNetValueHistoryService.getHistoryByFundCode(fundCode);
    }

    @GetMapping("/{fundCode}/range")
    public List<FundNetValueHistory> getHistoryInRange(
            @PathVariable String fundCode,
            @RequestParam("start") String start,
            @RequestParam("end") String end
    ) {
        LocalDate startDate = LocalDate.parse(start);
        LocalDate endDate = LocalDate.parse(end);
        return fundNetValueHistoryService.getHistoryInRange(fundCode, startDate, endDate);
    }

    @PostMapping("/add")
    public ResponseEntity<?> addNetValue(@RequestBody FundNetValueHistory history) {
        boolean exists = fundNetValueHistoryService.existsByFundCodeAndNetDate(history.getFundCode(), history.getNetDate());

        if (exists) {
            return ResponseEntity.status(HttpStatus.CONFLICT).body("记录已存在，无法重复添加！");
        }

        return ResponseEntity.ok(fundNetValueHistoryService.addNetValue(history));
    }

    @DeleteMapping("/delete/{id}")
    public void deleteNetValue(@PathVariable Long id) {
        fundNetValueHistoryService.deleteById(id);
    }
}
